package ar.edu.itba.twiteros.servlet;

import java.io.IOException;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.code.facebookapi.FacebookException;
import com.google.code.facebookapi.FacebookParam;
import com.google.code.facebookapi.Permission;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import ar.edu.itba.twiteros.domain.UserIds;
import ar.edu.itba.twiteros.util.Facebook;
import ar.edu.itba.twiteros.util.GrantTwitterAccess;

@SuppressWarnings("serial")
public class IndexServlet extends HttpServlet{

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
	}
	
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		RequestDispatcher dispacher= getServletContext().getRequestDispatcher("/index.jsp");

		String param= req.getParameter("fb_sig_user");
		
		
		if(param!=null){
			Long uid= Long.valueOf(param);
			
			Twitter twitter = new Twitter();
			GrantTwitterAccess grantAccess= new GrantTwitterAccess(twitter, uid);
			if(grantAccess.setAccessToken())
			{
				/*Facebook facebook= new Facebook(req.getParameter(FacebookParam.SESSION_KEY.toString()));
				try {
					if( !facebook.getClient().users_hasAppPermission(Permission.STATUS_UPDATE)|| 
							!facebook.getClient().users_hasAppPermission(Permission.PUBLISH_STREAM)){
						req.setAttribute("grant_access", true);
					}else{*/
						req.setAttribute("grant_access", false);
				//	}
				//} catch (FacebookException e1) {}
						
				req.setAttribute("access", true);
				try {
					req.setAttribute("user", twitter.getAuthenticatedUser());
					req.setAttribute("statuses", twitter.getFriendsTimeline());
					dispacher.forward(req, resp);
				} catch (TwitterException e) {
					req.setAttribute("error_message", e.getMessage());
					dispacher= getServletContext().getRequestDispatcher("/error.jsp");
					dispacher.forward(req, resp);
				}
			}else{
				req.setAttribute("access", false);
				req.setAttribute("url", grantAccess.getUrl());
			}

		}
		
		req.setAttribute("f_key", Facebook.getFb_appkey());
		dispacher.forward(req, resp);
	}


}
